<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<title>文件上传</title>
		<script src="./js/vue.js"></script>
		<!-- 引入样式 -->
		<link rel="stylesheet" href="css/elementui.css">
		<!-- 引入组件库 -->
		<script src="js/elementui.js"></script>
		<link href="https://releases.transloadit.com/uppy/v1.29.1/uppy.min.css" rel="stylesheet">
		<link href="./css/index.css" rel="stylesheet">
	</head>
	<body>
		<div id="app">
			<el-card class="box-card">
				<template #header>
					<div class="card-header">
						<span>上传说明(选填)</span>
					</div>
				</template>
				<el-input id="fileDescription" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="message"
					placeholder="详细的文件说明可以更好的找到文件哦(͏ ˉ ꈊ ˉ)✧˖°">
				</el-input>
			</el-card>

			<el-card class="box-card">
				<template #header>
					<div class="card-header">
						<span>文件上传</span>
					</div>
				</template>
				<div class="card-body">
					<div id="drag-drop-area"></div>
				</div>

				<div id="" style="display: flex;align-items: center; width: 90%;
					margin-top: 250px;position: relative; bottom: 50px;left: 5%;
					border-radius: 50px;
					height: 80px;line-height: 80px;" onclick="upload()">
					<input type="button" style=" background-color: #00aaff;
					outline: 0;
					border-radius: 50px;
					width: 100%; height: 100%; font-size: 30px;" id="upload-btn" value="一键上传" />
				</div>
			</el-card>

			<!-- <button type="primary" id="updataBtn"><span class="iconfont iconloading" id="loading" ></span>文件上传</button> -->
		</div>


	</body>
	<script src="https://releases.transloadit.com/uppy/v1.29.1/uppy.min.js"></script>
	<!-- 引入axios -->
	<script src="./js/axios.min.js"></script>
	<link rel="stylesheet" type="text/css" href="//at.alicdn.com/t/font_1938586_06k5hu69c21f.css">
	<script src="js/spark-md5.min.js"></script>
	<script>
		var axios = axios
		axios.defaults.baseURL = "https://gateway.xiaohong.work/api"

		// Vue部分
		new Vue({
			el: '#app',
			data() {
				return {
					message: "",
				};
			},
			created() {

			}
		})


		var FileList = []


		function sleep(numberMillis) {
			var now = new Date();
			var exitTime = now.getTime() + numberMillis;
			while (true) {
				now = new Date();
				if (now.getTime() > exitTime)
					return;
			}
		}
		var TUS_ENDPOINT = 'https://file.xiaohong.work/xiaohong/big/upload/'

		var COMPANION_ENDPOINT = 'http://localhost:3020'
		// Uppy初始化
		var uppy = Uppy.Core({
				// 上传文件前钩子
				onBeforeUpload: (files) => {
					const updatedFiles = {}
					Object.keys(files).forEach(async fileID => {
						updatedFiles[fileID] = {
							...files[fileID]
						}
						var md5
						var fileInfo
						console.log("FileList", FileList)
						console.log("fileID", fileID)
						for (var i = 0; i < FileList.length; i++) {
							if (FileList[i].id == fileID) {
								md5 = FileList[i].md5
								fileInfo = FileList[i].fileInfo
								console.log("找到了", FileList[i].fileInfo)
							}
						}

						if (fileInfo == "null") {
							console.log(fileID + "之前不存在")
							uppy.use(Uppy.Tus, {
								id: "bigUpload",
								endpoint: TUS_ENDPOINT
							})
						} else if (fileInfo == null) {
							// 数据还没到
							console.log("文件未加载完成")
						} else {
							console.log(fileID + "已经存在")
							// uppy.use(Uppy.XHRUpload, {
							// 	id: "againUpload",
							// 	// endpoint: 'http://127.0.0.1:9001/file/again?md5=' + md5
							// 	endpoint: 'http://127.0.0.1:80'
							// })
							updatedFiles[fileID].progress.bytesUploaded = updatedFiles[fileID].progress
								.bytesTotal
							updatedFiles[fileID].progress.percentage == 100
							updatedFiles[fileID].progress.uploadComplete = true
							updatedFiles[fileID].progress.uploadStarted = new Date().getTime()

							//秒传文件直接添加
							var fl = {}
							fl.md5 = md5
							fl.fileDescription = document.getElementById("fileDescription").value
							fl.fileName = updatedFiles[fileID].name
							// var ax = axios
							// ax.defaults.baseURL = "http://127.0.0.1:9001"
							// ax.defaults.baseURL = "https://gateway.xiaohong.work/api"
							// 更新数据
							for (var i = 0; i < FileList.length; i++) {
								if (FileList[i].id == fileID) {
									var newInfo = FileList[i]
									newInfo.fileInfo.fileDescription = fl.fileDescription
									newInfo.fileInfo.fileName = fl.fileName
									FileList.splice(i, 1, newInfo)
									console.log("更新后的数据", FileList)
								}
							}
							// 提交数据
							axios.post("/file/add/quick", {
								...fl,
							}).then(function(res) {
								console.log(JSON.stringify(res))
								// alert(res.data.message);
							}).catch(function(error) {
								console.log(error)
							})

							// uppy.use(Uppy.Tus, {
							//   endpoint: 'http://119.29.67.157:8080/xiaohong/upload?md5='+md5+"&output=json"
							// })
						}
					})
					console.log("上传前", updatedFiles)

					return updatedFiles
				}
			})
			.use(Uppy.Dashboard, {
				inline: true,
				target: '#drag-drop-area',
				note: '支持所有文件类型的断点上传',
				width: 900,
				hideUploadButton: true,
				height: 750,
				theme: 'bark',
				metaFields: [{
						id: 'name',
						name: 'Name',
						placeholder: 'file name'
					},
					{
						id: 'license',
						name: 'License',
						placeholder: 'specify license'
					},
					{
						id: 'caption',
						name: 'Caption',
						placeholder: 'describe what the image is about'
					},
					{
						id: 'public',
						name: 'Public',
						render: function({
							value,
							onChange
						}, h) {
							return h('input', {
								type: 'checkbox',
								onChange: (ev) => onChange(ev.target.checked ? 'on' : 'off'),
								defaultChecked: value === 'on'
							})
						}
					}
				],
				locale: {
					strings: {
						// When `inline: false`, used as the screen reader label for the button that closes the modal.
						closeModal: '关闭面板',
						// Used as the screen reader label for the plus (+) button that shows the “Add more files” screen
						addMoreFiles: '添加更多文件',
						// TODO
						addingMoreFiles: '添加更多文件',
						// Used as the header for import panels, e.g., “Import from Google Drive”.
						importFrom: 'Import from %{name}',
						// When `inline: false`, used as the screen reader label for the dashboard modal.
						dashboardWindowTitle: 'Uppy Dashboard Window (Press escape to close)',
						// When `inline: true`, used as the screen reader label for the dashboard area.
						dashboardTitle: 'Uppy Dashboard',
						// Shown in the Informer when a link to a file was copied to the clipboard.
						copyLinkToClipboardSuccess: 'Link copied to clipboard.',
						// Used when a link cannot be copied automatically — the user has to select the text from the
						// input element below this string.
						copyLinkToClipboardFallback: 'Copy the URL below',
						// Used as the hover title and screen reader label for buttons that copy a file link.
						copyLink: 'Copy link',
						// Used as the hover title and screen reader label for file source icons, e.g., “File source: Dropbox”.
						fileSource: '完成进度: %{name}',
						// Used as the label for buttons that accept and close panels (remote providers or metadata editor)
						done: '完成',
						// TODO
						back: '返回',
						// Used as the screen reader label for buttons that remove a file.
						removeFile: 'Remove file',
						// Used as the screen reader label for buttons that open the metadata editor panel for a file.
						editFile: 'Edit file',
						// Shown in the panel header for the metadata editor. Rendered as “Editing image.png”.
						editing: 'Editing %{file}',
						// Text for a button shown on the file preview, used to edit file metadata
						edit: '编辑',
						// Used as the screen reader label for the button that saves metadata edits and returns to the
						// file list view.
						finishEditingFile: 'Finish editing file',
						// TODO
						saveChanges: 'Save changes',
						// Used as the label for the tab button that opens the system file selection dialog.
						myDevice: '本地文件',
						// Shown in the main dashboard area when no files have been selected, and one or more
						// remote provider plugins are in use. %{browse} is replaced with a link that opens the system
						// file selection dialog.
						dropPasteImport: '将文件复制粘贴到这,或者 %{browse} 又或者导入文件从',
						// Shown in the main dashboard area when no files have been selected, and no provider
						// plugins are in use. %{browse} is replaced with a link that opens the system
						// file selection dialog.
						dropPaste: '拖拽或复制你的文件到这，又或者浏览本地文件',
						// TODO
						dropHint: '将你的文件拖拽到这',
						// This string is clickable and opens the system file selection dialog.
						browse: '浏览本地文件',
						// Used as the hover text and screen reader label for file progress indicators when
						// they have been fully uploaded.
						uploadComplete: '上传完成',
						// TODO
						uploadPaused: 'Upload paused',
						// Used as the hover text and screen reader label for the buttons to resume paused uploads.
						resumeUpload: 'Resume upload',
						// Used as the hover text and screen reader label for the buttons to pause uploads.
						pauseUpload: '暂停',
						// Used as the hover text and screen reader label for the buttons to retry failed uploads.
						retryUpload: '重试',
						// Used as the hover text and screen reader label for the buttons to cancel uploads.
						cancelUpload: '取消',

						// Used in a title, how many files are currently selected
						xFilesSelected: {
							0: '%{smart_count} file selected',
							1: '%{smart_count} files selected'
						},
						// TODO
						uploadingXFiles: {
							0: 'Uploading %{smart_count} file',
							1: 'Uploading %{smart_count} files'
						},
						// TODO
						processingXFiles: {
							0: 'Processing %{smart_count} file',
							1: 'Processing %{smart_count} files'
						},

						// The "powered by Uppy" link at the bottom of the Dashboard.
						// **NOTE**: This string is called `poweredBy2` for backwards compatibility reasons.
						// See https://github.com/transloadit/uppy/pull/2077
						poweredBy2: '本服务由小鸿同学提供',

						// @uppy/status-bar strings:
						uploading: '上传中',
						complete: '上传完成'
					}
				}
			})
			.use(Uppy.Webcam, {
				inline: true,
				target: Uppy.Dashboard
			})
			// .use(Uppy.ScreenCapture, {
			// 	target: Uppy.Dashboard
			// })
			.use(Uppy.ImageEditor, {
				target: Uppy.Dashboard
			})
			.use(Uppy.GoogleDrive, {
				target: Uppy.Dashboard,
				companionUrl: COMPANION_ENDPOINT
			})
			.use(Uppy.Instagram, {
				target: Uppy.Dashboard,
				companionUrl: COMPANION_ENDPOINT
			})
			.use(Uppy.Dropbox, {
				target: Uppy.Dashboard,
				companionUrl: COMPANION_ENDPOINT
			})
			.use(Uppy.Box, {
				target: Uppy.Dashboard,
				companionUrl: COMPANION_ENDPOINT
			})
			.use(Uppy.Facebook, {
				target: Uppy.Dashboard,
				companionUrl: COMPANION_ENDPOINT
			})
			.use(Uppy.OneDrive, {
				target: Uppy.Dashboard,
				companionUrl: COMPANION_ENDPOINT
			})
			.use(Uppy.Url, {
				target: Uppy.Dashboard,
				companionUrl: COMPANION_ENDPOINT
			})


		// uppy.setMeta({ callback_url:'https://gateway.xiaohong.work/api/file/callback'})//自定义参数与普通上传类似（虽然支持自定义，建议不要自定义，海量文件情况下，自定义很可能给自已给埋坑）


		uppy.on('file-added', (file) => {
			// document.getElementById("updataBtn").removeAttribute()("disabled");
			document.getElementById("upload-btn").setAttribute("disabled", "disabled");
			document.getElementById("upload-btn").setAttribute("value", "文件加载中....");
			var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
				fileInfo = file.data
			chunkSize = 2097152, // Read in chunks of 2MB
				chunks = Math.ceil(fileInfo.size / chunkSize),
				currentChunk = 0,
				spark = new SparkMD5.ArrayBuffer(),
				fileReader = new FileReader();

			fileReader.onload = async function(e) {
				// console.log('read chunk nr', currentChunk + 1, 'of', chunks);
				spark.append(e.target.result); // Append array buffer
				currentChunk++;

				if (currentChunk < chunks) {
					loadNext();
				} else {
					// 这里注意 多次获取的值不一样
					// console.info('computed hash', spark.end()); // Compute hash
					var md5 = spark.end()
					console.info('computed hash', md5); // Compute hash
					var fileInfo
					// var axo = axios
					// axios.defaults.baseURL ="https://gateway.xiaohong.work/api"
					// axo.defaults.baseURL ="http://127.0.0.1:9001"
					await axios.get("/file/searchByMD5?md5=" + md5)
						.then(function(res) {
							console.log(JSON.stringify(res))
							// console.log(res.data.message);
							console.log(res.data)
							fileInfo = res.data.data
							// 去除loading和打开按钮
							// document.getElementById("upload-btn").innerHTML("<p>等待上传</p>");
							document.getElementById("upload-btn").removeAttribute("disabled");
							document.getElementById("upload-btn").setAttribute("value", "一键上传");
						}).catch(function(error) {
							console.log(error)
						})

					// 获取文件信息
					FileList.push({
						id: file.id,
						md5: md5,
						fileInfo: fileInfo
					})
					uppy.getPlugin('Dashboard').setOptions({
						hideUploadButton: false
					})
					console.log("添加后文件集合", FileList)
				}
			};

			fileReader.onerror = function() {
				console.warn('oops, something went wrong.');
			};

			function loadNext() {
				var start = currentChunk * chunkSize,
					end = ((start + chunkSize) >= fileInfo.size) ? fileInfo.size : start + chunkSize;

				fileReader.readAsArrayBuffer(blobSlice.call(fileInfo, start, end));
			}

			loadNext();

		})


		function upload() {
			if (FileList.length == 0 || FileList == null) {
				alert("你还没有添加文件哦~")
				return
			}
			var flag = true
			FileList.forEach(file => {
				if (file.fileInfo == null) {
					flag = false
				}
			})
			if (flag) {
				if (document.getElementById("fileDescription").value == '') {
					alert("请先填写文件简介哦~")
				} else {
					uppy.upload()
					// .then((result) => {
					//   console.info('Successful uploads:', result.successful)

					//   if (result.failed.length > 0) {
					//     console.error('Errors:')
					//     result.failed.forEach((file) => {
					//       console.error(file.error)
					//     })
					//   }
					// })
				}
			} else {
				alert("文件加载中...")
			}
		}


		function isUpload() {
			var flag = true
			FileList.forEach(file => {
				if (file.fileInfo == null) {
					flag = false
				}
			})
			if (flag) {
				// return true
				document.getElementById("upload-btn").removeAttribute("disabled");
				document.getElementById("upload-btn").setAttribute("value", "一键上传");
			} else {
				// 不可上传
				document.getElementById("upload-btn").setAttribute("disabled", "disabled");
				document.getElementById("upload-btn").setAttribute("value", "文件加载中....");
				// return false
			}
		}

		uppy.on('file-removed', (file, reason) => {
			console.log('Removed file', file)
			for (var i = 0; i < this.FileList.length; i++) {
				if (this.FileList[i].id == file.id) {
					this.FileList.splice(i, 1)
				}
			}
			isUpload()
			console.log("删除文件集合", FileList)
		})

		var fileInfo = {
			fileName: '',
			fileSize: '',
			extension: '',
			fileGroup: 'xiaohong',
			fileDescription: '',
			domain: 'https://file.xiaohong.work',
			path: "",
			md5: ''
		}

		uppy.on('complete', async result => {
			console.log('successful files:', result.successful)
			console.log('failed files:', result.failed)
			if (result.successful.length > 0) {
				// 代表上传成功 遍历保存数据
				for (var i = 0; i < result.successful.length; i++) {
					console.log(JSON.stringify(result.successful[i]))
					this.fileInfo.fileName = result.successful[i].name
					// this.fileInfo.fileSize = result.successful[i].size
					this.fileInfo.extension = result.successful[i].name.split('.').pop()
					this.fileInfo.fileDescription = document.getElementById("fileDescription").value
					// console.log("value:" + document.getElementById("fileDescription").value)
					// axios.defaults.baseURL = ''
					// axios.defaults.baseURL = 'https://gateway.xiaohong.work/api'
					// axios.defaults.baseURL = 'http://119.29.67.157:9004'
					// axios.defaults.baseURL = 'http://127.0.0.1:9001'



					// 删除元素
					// for (var i = 0; i < this.FileList.length; i++) {
					// 	if(this.FileList[i].id == result.successful[i].id){
					// 		this.FileList[i].splice(i,1)
					// 	}
					// }
					this.fileInfo.path = "/xiaohong" + result.successful[i].uploadURL.split('/xiaohong').pop()
					this.fileInfo.md5 = result.successful[i].uploadURL.split('/').pop()
					axios.post("/file/add", {
						...this.fileInfo,
					}).then(function(res) {
						console.log(JSON.stringify(res))
						console.log(res.data.message);
					}).catch(function(error) {
						console.log(error)
					})


				}

			}
		})
	</script>
</html>
